package com.hmall.order.listener;


import com.hmall.common.feign.ItemClientFeign;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderInfo;
import com.hmall.order.service.OrderDetailService;
import com.hmall.order.service.impl.OrderLogisticsService;
import com.hmall.order.service.impl.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 监听失效订单,如果有就会进行修改
 */
@Component
@Slf4j
public class OrderListener {

    @Resource
    private OrderService orderService;

    @Resource
    private ItemClientFeign itemClientFeign;
    @Resource
    private OrderDetailService orderDetailService;
    @Resource
    private OrderLogisticsService orderLogisticsService;

    /**
     * 接受过期信息
     *
     * @param orderInfo
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "order.queue", declare = "true"),
            exchange = @Exchange(name = "dl.ttl.exchange",delayed = "true"),
            key = "dl"
    ))
    public void handleOrderMsg(OrderInfo orderInfo) {
        log.info("处理失效订单：" + orderInfo.getId() + ":" + new Date());
        //先判断该订单是否已经支付，如果还是未支付，才进行修改（status=5,取消时间更新，把库存还原）
        Order order = orderService.getById(orderInfo.getId());
        if (order.getStatus() == 1) {
            //设置订单状态
            orderService.updateStatus(orderInfo.getId(), 5);
            //恢复库存
            itemClientFeign.updateStock(orderInfo.getItemId(), orderInfo.getNum());
            log.info("订单已取消");
        }

    }
}

//    public void handleOrderMsg(OrderInfo orderInfo){
//
//        log.info("接收到 dl.ttl.queue的延迟消息：{}", orderInfo);
//        //调用清理订单的方法，检查orderid对应的status是否已支付，如果没有改状态恢复库存
//        //清理订单自己实现
//
//        Order order = orderService.getById(orderInfo);
//        Integer status = order.getStatus();
//        if (status == 1){
//            //删除订单
//            orderService.removeById(orderInfo);
//
//            //删除订单相信信息
//            LambdaQueryWrapper<OrderDetail> orderDetailQueryWrapper = new LambdaQueryWrapper<>();
//            orderDetailQueryWrapper.eq(OrderDetail::getOrderId,orderInfo);
//            orderDetailService.remove(orderDetailQueryWrapper);
//
//            //删除订单对应地址信息
//            LambdaQueryWrapper<OrderLogistics> logisticsQueryWrapperQueryWrapper = new LambdaQueryWrapper<>();
//            orderLogisticsService.remove(logisticsQueryWrapperQueryWrapper);
//
//            //修改库存
//            OrderDetail orderDetail = orderDetailService.getOne(orderDetailQueryWrapper);
//            itemClientFeign.updateStock(orderDetail.getItemId(),orderDetail.getNum());
//
//        }
//    }
